package com.migu.rbac.message;

import com.migu.rbac.util.RandomUtils;
import com.migu.rbac.vo.MsgRes;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description TODO :
 * @Author: zj
 * @Date: 14:26 2019/6/4
 * @Version 1.0
 **/
@Service
public class RbacMessageService {
    private static Log log = LogFactory.getLog(RbacMessageService.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RbacSendMsgService rbacSendMsgService;

    @Value("${sendmessage.save-time}")
    private String MSG_SAVE_TIME;



    public MsgRes sendMsg(String phoneNum, String userId,String template) {
        Map<String, Object> map = new HashMap<String, Object>();
        StringBuffer msgKey = new StringBuffer();
        String msgValue = "";

        msgKey.append(phoneNum).append(userId);
        msgValue = (String) redisTemplate.opsForValue().get(msgKey.toString());
        log.info("redis value before:" + msgValue);
        if (StringUtils.isEmpty(msgValue)) {
            msgValue = RandomUtils.getRandomNumber(4);
            redisTemplate.opsForValue().set(msgKey.toString(), msgValue, Long.parseLong(MSG_SAVE_TIME), TimeUnit.MILLISECONDS);
        }
        log.info("redis value after:" + msgValue);
        map.put("message", template.replace("{VERIFY_CODE}", msgValue));
        map.put("phoneNumber", phoneNum);
        String xml = rbacSendMsgService.sendMessage(map);
        log.info("=============调用信息发送接口返回信息xml=" + xml);

        MsgRes msgRes = new MsgRes();
        if (xml == "sendMessage timeout") {
            msgRes.setMessage(xml);
        } else {
            msgRes = parseSimpleXml(xml);
        }
        log.info("message:" + msgRes);
        return msgRes;
    }

    private static MsgRes parseSimpleXml(String xml) {
        MsgRes msgRes = null;
        try {
            if (xml != null && !"".equals(xml)) {
                Document doc = DocumentHelper.parseText(xml);
                Element root = doc.getRootElement();
                String resultCode = root.elementText("result_code");
                String resultDesc = root.elementText("result_desc");
                msgRes = new MsgRes();
                msgRes.setCode(resultCode);
                msgRes.setMessage(resultDesc);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return msgRes;
    }
}
